using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;

namespace SG3L_RAG.Domain.Entities
{
    public class Conversation : EntityBase
    {
        public Guid UserId { get; private set; }
        public User? User { get; private set; }
        public string Title { get; private set; } = string.Empty;
        private readonly List<Message> _messages = new();
        public bool IsCollect { get; private set; } = false;
        public IReadOnlyCollection<Message> Messages => _messages.AsReadOnly();

        // EF Core 需要的无参构造函数
        public Conversation() { }

        // 业务构造函数
        private Conversation(Guid userId, string title = "新对话")
        {
            UserId = userId;
            Title = title;
            CreatedAt = DateTime.UtcNow;
        }

        // 收藏/取消收藏
        public void SetCollect(bool isCollect)
        {
            IsCollect = isCollect;
        }

        // 工厂方法
        public static Conversation Create(Guid userId)
        {
            return new Conversation(userId);
        }

        public static Conversation Create(Guid userId, string title)
        {
            return new Conversation(userId, title);
        }

        public void AddMessage(Message message)
        {
            _messages.Add(message);
        }

        // 获取最近N条消息
        public IEnumerable<Message> GetRecentMessages(int count)
        {
            if (count <= 0) return new List<Message>();
            int skip = Math.Max(0, _messages.Count - count);
            return _messages.Skip(skip);
        }

        // 获取最后一条消息
        public Message? GetLastMessage()
        {
            if (_messages.Count == 0) return null;
            return _messages[_messages.Count - 1];
        }
    }
}
